// import { Message } from 'element-ui';
// import axiosRetry from 'axios-retry';
// import { authUtils } from '@/util/auth';
// import { router } from '@/router'
import router from '@/router'
import axios from 'axios';
import type { AxiosError, AxiosInstance, AxiosPromise, AxiosRequestConfig, AxiosResponse } from 'axios';
import qs from 'qs';


export interface IDataWithError<T> {
  Data: T;
  Code: number;
  Msg: string;
}


class HttpService {
  private http!: AxiosInstance;
  constructor() {
    this.http = axios.create({
      // baseURL: authUtils.getBaseURL(),
      baseURL: "/gaoqian/api",
      timeout: 60000,
      paramsSerializer: function (params) {
        return qs.stringify(params, { arrayFormat: 'repeat' })

      }

    });
    this.addInterceptors(this.http);
  }


  actionGet<T>(action: string, params: object) {
    params.api_action = action
    return this.handleErrorWrapper<T>(this.http.get("/", { params: params }));
  }

  actionPost<T>(action: string, param: unknown) {
    param.api_action = action
    return this.handleErrorWrapper<T>(this.http.post("/", param, config));
  }



  get<T>(url: string, config?: AxiosRequestConfig) {
    return this.handleErrorWrapper<T>(this.http.get(url, config));
  }

  post<T>(url: string, param: unknown, config?: AxiosRequestConfig) {
    return this.handleErrorWrapper<T>(this.http.post(url, param, config));
  }

  postDownload<T>(url: string, param: unknown) {
    return this.handleErrorWrapper<T>(this.http.post(url, param, { responseType: 'arraybuffer' }));
  }

  put<T>(url: string, param: unknown, config?: AxiosRequestConfig) {
    return this.handleErrorWrapper<T>(this.http.put(url, param, config));
  }

  delete<T>(url: string, param: unknown, config?: AxiosRequestConfig) {
    return this.handleErrorWrapper<T>(this.http.delete(url, { data: param, ...config }));
  }

  private addInterceptors(http: AxiosInstance) {
    // // 一、请求拦截器
    // http.interceptors.request.use((config) => {
    //   // 1、添加token和项目id
    //   const token = authUtils.getToken();
    //   if (token) {
    //     config.headers['Authorization'] = 'Bearer ' + token;
    //     config.headers['ProjectId'] = authUtils.getProjectId();
    //   }

    //   // 2、验证请求状态码
    //   config.validateStatus = (status) => {
    //     switch (status) {
    //       case 401:
    //         const instance = Message.error('用户信息过期，请重新登录');
    //         setTimeout(() => {
    //           instance.close();
    //           router.push('/login');
    //         }, 1000);
    //         break;
    //       default:
    //         console.warn(`status= ${status}`);
    //         break;
    //     }
    //     return status >= 200 && status < 400;
    //   };

    //   return config;
    // });

    // 二、响应拦截器
    http.interceptors.response.use(
      (response: AxiosResponse) => {
        if (response.data != null && response.data.CODE == "SessionNotAuthed") {
          localStorage.removeItem('user');
          router.push({ path: '/login' })
        }
        return response
      },
      (error) => {
        return Promise.reject(error);
      },
    );
  }

  private async handleErrorWrapper<T>(p: AxiosPromise): Promise<IDataWithError<T>> {
    return p
      .then((response) => {
        return response.data;
      })
      .catch((error: AxiosError) => {
        return {
          ...error.response?.data,
        };
      });
  }
}

export const httpService = new HttpService();

